package com.example.demo.strategy.impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;

@Service
public class LocalUploadStrategy extends AbstractUploadStrategyImpl{

    @Value("${upload.local.path}")
    private String localPath;

    @Value("${upload.local.url}")
    private String localUrl;

    @Override
    public Boolean exists(String filePath) {
        return new File(localPath + filePath).exists();
    }

    @Override
    public void uploadFile(String name, String path, InputStream inputStream) throws Exception {
        //判断文件夹是否存在
        File directory = new File(localPath + path);
        //如果不存在创建文件夹,创建失败则文件上传失败
        if (!directory.isDirectory()){
            if (!directory.mkdirs()){
                throw new Exception("文件上传失败");
            }
        }

        //写入文件
        File file = new File(localPath + path + name);
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(file.toPath()));
        byte[] bytes = new byte[1024];
        int length;
        while ((length = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, length);
        }
        bos.flush();
        bos.close();
        bis.close();
        inputStream.close();

    }

    @Override
    public String getFileAccessUrl(String path) {
        return localUrl + path;
    }
}
